<?php
// 设置响应头，允许跨域请求
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 读取航班数据文件
$filePath = 'hangban.json';
if (!file_exists($filePath)) {
    echo json_encode(['error' => '航班数据文件不存在']);
    exit;
}

$jsonData = file_get_contents($filePath);
$flightData = json_decode($jsonData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(['error' => '航班数据文件格式错误']);
    exit;
}

// 获取请求参数
$action = $_GET['action'] ?? '';
$fromCity = $_GET['from'] ?? '';
$toCity = $_GET['to'] ?? '';

// 处理不同的API请求
switch ($action) {
    case 'all_cities':
        // 获取所有城市列表（按拼音排序）
        $cities = getAllCities($flightData);
        echo json_encode(['cities' => $cities]);
        break;
    
    case 'search_flights':
        // 搜索航班（直达和中转，或单条件查询）
        $result = searchFlights($flightData, $fromCity, $toCity);
        echo json_encode($result);
        break;
    
    default:
        echo json_encode(['error' => '未知的请求类型']);
}

/**
 * 中文城市按拼音排序的辅助函数
 */
function sortByPinyin($city1, $city2) {
    // 使用PHP的intl扩展进行拼音排序
    if (extension_loaded('intl')) {
        $collator = new Collator('zh_CN');
        return $collator->compare($city1, $city2);
    } else {
        // 如果没有intl扩展，使用ASCII值比较（不完美但可用）
        return strcmp($city1, $city2);
    }
}

/**
 * 获取所有城市列表（按拼音排序）
 */
function getAllCities($flightData) {
    $cities = [];
    
    // 收集所有出发城市
    foreach ($flightData as $from => $destinations) {
        $cities[] = $from;
        // 收集所有目的地城市
        foreach ($destinations as $to) {
            $cities[] = $to;
        }
    }
    
    // 去重
    $cities = array_unique($cities);
    
    // 按拼音排序
    usort($cities, 'sortByPinyin');
    
    return $cities;
}

/**
 * 搜索航班（支持单条件和双条件查询）
 */
function searchFlights($flightData, $fromCity, $toCity) {
    // 如果只选择了出发地
    if (!empty($fromCity) && empty($toCity)) {
        return getDestinationsFromCity($flightData, $fromCity);
    }
    
    // 如果只选择了目的地
    if (empty($fromCity) && !empty($toCity)) {
        return getOriginsToCity($flightData, $toCity);
    }
    
    // 如果出发地和目的地都选择了
    if (!empty($fromCity) && !empty($toCity)) {
        return searchDirectAndTransferFlights($flightData, $fromCity, $toCity);
    }
    
    // 如果都没选择，返回空结果
    return [
        'direct_flights' => [],
        'transfer_flights' => []
    ];
}

/**
 * 获取从指定出发地可达的所有目的地
 */
function getDestinationsFromCity($flightData, $fromCity) {
    $destinations = [];
    
    if (isset($flightData[$fromCity])) {
        foreach ($flightData[$fromCity] as $destination) {
            $destinations[] = [
                'from' => $fromCity,
                'to' => $destination,
                'type' => 'direct'
            ];
        }
    }
    
    return [
        'destinations' => $destinations,
        'total_count' => count($destinations),
        'from_city' => $fromCity
    ];
}

/**
 * 获取所有能到达指定目的地的出发地
 */
function getOriginsToCity($flightData, $toCity) {
    $origins = [];
    
    foreach ($flightData as $from => $destinations) {
        if (in_array($toCity, $destinations)) {
            $origins[] = [
                'from' => $from,
                'to' => $toCity,
                'type' => 'direct'
            ];
        }
    }
    
    return [
        'origins' => $origins,
        'total_count' => count($origins),
        'to_city' => $toCity
    ];
}

/**
 * 查找直达和中转航班（最多2次中转）
 */
function searchDirectAndTransferFlights($flightData, $fromCity, $toCity) {
    $directFlights = [];
    $transferFlights = [];
    
    // 检查直达航班
    if (isset($flightData[$fromCity]) && in_array($toCity, $flightData[$fromCity])) {
        $directFlights[] = [
            'from' => $fromCity,
            'to' => $toCity,
            'type' => 'direct',
            'transfer_count' => 0,
            'segments' => [[$fromCity, $toCity]]
        ];
    }
    
    // 查找1次中转航班（2段航线）
    $firstTransferRoutes = findTransferRoutes($flightData, $fromCity, $toCity, 1);
    foreach ($firstTransferRoutes as $route) {
        $transferFlights[] = [
            'from' => $fromCity,
            'to' => $toCity,
            'transfer_city' => $route['transfer_cities'][0],
            'transfer_cities' => $route['transfer_cities'],
            'type' => 'transfer',
            'transfer_count' => 1,
            'segments' => $route['segments']
        ];
    }
    
    // 查找2次中转航班（3段航线）
    $secondTransferRoutes = findTransferRoutes($flightData, $fromCity, $toCity, 2);
    foreach ($secondTransferRoutes as $route) {
        $transferFlights[] = [
            'from' => $fromCity,
            'to' => $toCity,
            'transfer_cities' => $route['transfer_cities'],
            'type' => 'transfer',
            'transfer_count' => 2,
            'segments' => $route['segments']
        ];
    }
    
    return [
        'direct_flights' => $directFlights,
        'transfer_flights' => $transferFlights,
        'from_city' => $fromCity,
        'to_city' => $toCity
    ];
}

/**
 * 查找中转方案（支持多次中转）
 * @param array $flightData 航班数据
 * @param string $fromCity 出发城市
 * @param string $toCity 目的地城市
 * @param int $maxTransfers 最大中转次数
 * @return array 中转方案列表
 */
function findTransferRoutes($flightData, $fromCity, $toCity, $maxTransfers = 1) {
    $routes = [];
    
    if ($maxTransfers == 1) {
        // 1次中转（A → B → C）
        if (isset($flightData[$fromCity])) {
            foreach ($flightData[$fromCity] as $transferCity1) {
                if ($transferCity1 != $toCity && isset($flightData[$transferCity1])) {
                    foreach ($flightData[$transferCity1] as $city) {
                        if ($city == $toCity) {
                            $routes[] = [
                                'transfer_cities' => [$transferCity1],
                                'segments' => [[$fromCity, $transferCity1], [$transferCity1, $toCity]]
                            ];
                        }
                    }
                }
            }
        }
    } elseif ($maxTransfers == 2) {
        // 2次中转（A → B → C → D）
        if (isset($flightData[$fromCity])) {
            foreach ($flightData[$fromCity] as $transferCity1) {
                if ($transferCity1 != $toCity && isset($flightData[$transferCity1])) {
                    foreach ($flightData[$transferCity1] as $transferCity2) {
                        if ($transferCity2 != $fromCity && $transferCity2 != $toCity && isset($flightData[$transferCity2])) {
                            foreach ($flightData[$transferCity2] as $city) {
                                if ($city == $toCity) {
                                    $routes[] = [
                                        'transfer_cities' => [$transferCity1, $transferCity2],
                                        'segments' => [
                                            [$fromCity, $transferCity1],
                                            [$transferCity1, $transferCity2],
                                            [$transferCity2, $toCity]
                                        ]
                                    ];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    return $routes;
}